//
//  NewsViewController.m
//  CarWorld
//
//  Created by 曹杨杨 on 15/3/25.
//  Copyright (c) 2015年 CarWorldTeam. All rights reserved.
//

#import "NewsViewController.h"
#import "c_NewsListData.h"
#import "UIImageView+WebCache.h"
#import "NewsImageScrollView.h"
#import "NewsTableCell.h"
#import "NewDetailViewController.h"
#import "NewsTabulationData.h"

//第三方
#import "AFNetworking.h"

#define CELLHEIGHT 80
@interface NewsViewController ()
@property (nonatomic, retain) UIActivityIndicatorView *activityIndicator;
@property(nonatomic, retain) NSMutableArray *newsArray;
@property(nonatomic, retain) NewsImageScrollView *newsScrollView;
//存放被监听的对象
@property(nonatomic, retain) NSMutableArray *obserArray;

@property (nonatomic, retain) NSMutableArray *tabulationArray;
@property (nonatomic, retain) UITableView *TView;
@property (nonatomic, retain) UIRefreshControl *control;
@end
@implementation NewsViewController

-(void)dealloc
{
    [_activityIndicator release];
    [_newsScrollView release];
    [_TView release];
    [_tabulationArray release];
    [_newsArray release];
    [_control release];
    [super dealloc];
}


- (void)addRefurbish
{
    self.activityIndicator = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
    CGFloat px = [UIScreen mainScreen].bounds.size.width/2-50;
    _activityIndicator.frame = CGRectMake(px, 100, 100, 50);
    UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(0, 30, 100, 20)];
    lbl.text = @"玩命加载中...";
    lbl.font = [UIFont systemFontOfSize:10];
    lbl.textAlignment = NSTextAlignmentCenter;
    [_activityIndicator addSubview:lbl];
    [lbl     release];
    [_activityIndicator startAnimating];
    [self.view addSubview:_activityIndicator];
    self.view.userInteractionEnabled = NO;
    
}
- (void)stopAnimating
{
    [_activityIndicator stopAnimating];
    self.view.userInteractionEnabled = YES;
}
//首页轮播图
- (void)getNewsScrollUrl
{
    [self addRefurbish];
    NSURL *url = [NSURL URLWithString:@"http://mobile.auto.sohu.com/mcms/external/getFocusNews.at?newsType=11"];
    NSURLRequest *requst = [NSURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:requst queue:[[[NSOperationQueue alloc] autorelease] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (data != nil) {
            dispatch_async(dispatch_get_main_queue(), ^{
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves|NSJSONReadingMutableContainers error:nil];
                NSArray *arr = dic[@"RESULT"];
                self.newsArray = [NSMutableArray array];
                for (NSDictionary *pdic in arr) {
                    c_NewsListData *cellData = [[c_NewsListData alloc] init];
                    [cellData setValuesForKeysWithDictionary:pdic];
                    [_newsArray addObject:cellData];
                    [cellData release];
                }
                
            });
          dispatch_async(dispatch_get_main_queue(), ^{
              [_newsScrollView.AAA setImageWithURL:[NSURL URLWithString:[_newsArray[0] header_img_url]]];
              _newsScrollView.label1.text = [_newsArray[0] title];
              [_newsScrollView.BBB setImageWithURL:[NSURL URLWithString:[_newsArray[1] header_img_url]]];
              _newsScrollView.label2.text = [_newsArray[1] title];
              [_newsScrollView.CCC setImageWithURL:[NSURL URLWithString:[_newsArray[2] header_img_url]]];
              _newsScrollView.label3.text = [_newsArray[2] title];
              [_newsScrollView.DDD setImageWithURL:[NSURL URLWithString:[_newsArray[3] header_img_url]]];
              _newsScrollView.label4.text = [_newsArray[3] title];
              [self.view drawRect:self.view.frame];
//              NSLog(@"%@",[_newsArray[0] header_img_url]);
              [self stopAnimating];
          });

            
        }
    }];
    
}

//- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
//{
//    NSLog(@"go to ");
//    UIButton *btn = (UIButton *)context;
//    UIImage *image = (UIImage *)[change objectForKey:@"new"];
//    [btn setImage:image forState:UIControlStateNormal];
//

- (void)first
{
//    NewDetailViewController *newDetail = [[NewDetailViewController alloc] init];
//    
//    newDetail.newsId = [_newsArray[0] Id];
//    [self.navigationController pushViewController:newDetail animated:YES];
//    [newDetail release];
    
    NewDetailViewController *newsDetail = [[NewDetailViewController alloc] init];
    newsDetail.newsId = [_newsArray[0] Id];
    UINavigationController *newNVC = [[UINavigationController alloc] initWithRootViewController:newsDetail];
    [newNVC setModalTransitionStyle:UIModalTransitionStyleFlipHorizontal];
    [self presentViewController:newNVC animated:YES completion:^{
        
    }];
    [newsDetail release];
    
}

- (void)two
{
    NewDetailViewController *newDetail = [[NewDetailViewController alloc] init];
    
    newDetail.newsId = [_newsArray[1] Id];
    UINavigationController *newNVC = [[UINavigationController alloc] initWithRootViewController:newDetail];
    [newNVC setModalTransitionStyle:UIModalTransitionStyleFlipHorizontal];
    [self presentViewController:newNVC animated:YES completion:^{
        
    }];
    [newDetail release];
}

- (void)three
{
    NewDetailViewController *newDetail = [[NewDetailViewController alloc] init];
    
    newDetail.newsId = [_newsArray[2] Id];
    UINavigationController *newNVC = [[UINavigationController alloc] initWithRootViewController:newDetail];
    [newNVC setModalTransitionStyle:UIModalTransitionStyleFlipHorizontal];
    [self presentViewController:newNVC animated:YES completion:^{
        
    }];
    [newDetail release];
}

- (void)four
{
    NewDetailViewController *newDetail = [[NewDetailViewController alloc] init];
    
    newDetail.newsId = [_newsArray[3] Id];
    UINavigationController *newNVC = [[UINavigationController alloc] initWithRootViewController:newDetail];
    [newNVC setModalTransitionStyle:UIModalTransitionStyleFlipHorizontal];
    [self presentViewController:newNVC animated:YES completion:^{
        
    }];
    [newDetail release];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.newsArray = [NSMutableArray array];
    self.obserArray = [NSMutableArray array];
    [self getNewsScrollUrl];
    self.navigationItem.title = @"新闻时讯";
    
    //创建tableView
    CGRect rect = [UIScreen mainScreen].bounds;
    CGFloat width = rect.size.width;
    CGFloat height = rect.size.height;
    _TView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, width, height) style:UITableViewStylePlain];
    _TView.dataSource = self;
    _TView.delegate = self;
    _TView.separatorStyle = UITableViewCellSelectionStyleNone;
    
    _newsScrollView = [[NewsImageScrollView  alloc] initWithFrame:CGRectMake(0, 94, width, width/2)];
    _newsScrollView.contentSize = CGSizeMake(rect.size.width*4, width/2);
    _newsScrollView.pagingEnabled = YES;
    [_newsScrollView.btn1 addTarget:self action:@selector(first) forControlEvents:UIControlEventTouchUpInside];
    [_newsScrollView.btn2 addTarget:self action:@selector(two) forControlEvents:UIControlEventTouchUpInside];
    [_newsScrollView.btn3 addTarget:self action:@selector(three) forControlEvents:UIControlEventTouchUpInside];
    [_newsScrollView.btn4 addTarget:self action:@selector(four) forControlEvents:UIControlEventTouchUpInside];
    
    _TView.tableHeaderView = _newsScrollView;
    [self.view addSubview:_TView];

    [_TView release];
    [_newsScrollView release];
    
    //TableViewCell的数据
    [self getNewURL];
    
    
    
    //集成刷新控件
    [self setupRefresh];
    
    
}

- (void)setupRefresh
{
    UIRefreshControl *control = [[UIRefreshControl alloc] init];
    self.control = control;
    [control addTarget:self action:@selector(refreshStateChange:) forControlEvents:UIControlEventValueChanged];
    [_TView addSubview:control];
    [control release];
}

- (void)refreshStateChange:(UIRefreshControl *)control
{
    
    //~~~~~~~~~~~~~~~~~~ 删除所有监听 ~~~~~~~~~~~~~~~~
    NSInteger count = self.obserArray.count;
    for (int i; i<count; i++) {
        NewsTabulationData *cellData = _obserArray[i];
        [cellData removeObserver:self forKeyPath:@"image"];
    }
    [self.obserArray removeAllObjects];
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    
//    AFHTTPRequestOperationManager *agr = [AFHTTPRequestOperationManager manager];
    //[self getNewURL];
    NSURL *url = [NSURL URLWithString:@"http://mobile.auto.sohu.com/mcms/external/getNews.at?newsType=11&pageSize=20"];
    NSMutableURLRequest *requst = [NSMutableURLRequest requestWithURL:url];
    
    NSData *data =[NSURLConnection sendSynchronousRequest:requst returningResponse:nil error:nil];
    if (data) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves|NSJSONReadingMutableContainers error:nil];
            NSArray *array = dic[@"RESULT"];
            NSMutableArray *tempArr = [[NSMutableArray alloc] init];
            for (NSDictionary *dic in array) {
                NSLog(@"parie");
                NewsTabulationData *cellData = [[NewsTabulationData alloc] init];
                [cellData setValuesForKeysWithDictionary:dic];
                [tempArr addObject:cellData];
                [cellData release];
            }
//        NSMutableArray *ptArray = _tabulationArray;
        _tabulationArray = tempArr;
        [self.TView reloadData];
//        [ptArray removeAllObjects];
//        [ptArray release];
        }
    [self stopAnimating];
    
    [control endRefreshing];
}

- (void)refreshUrl
{
    NSURL *url = [NSURL URLWithString:@"http://mobile.auto.sohu.com/mcms/external/getNews.at?newsType=11&pageSize=20"];
    NSMutableURLRequest *requst = [NSMutableURLRequest requestWithURL:url];
    
    NSData *data =[NSURLConnection sendSynchronousRequest:requst returningResponse:nil error:nil];
    if (data) {
        [self parisData:data];
    }
    [self.TView reloadData];
}


- (void)getNewURL
{
    [self addRefurbish];
    NSURL *url = [NSURL URLWithString:@"http://mobile.auto.sohu.com/mcms/external/getNews.at?newsType=11&pageSize=20"];
    NSMutableURLRequest *requst = [NSMutableURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:requst queue:[[[NSOperationQueue alloc] init] autorelease] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (data) {
            [self parisData:data];
        }
    }];
}
- (void)parisData:(NSData *)data
{
    if (data) {
        dispatch_async(dispatch_get_main_queue(), ^{
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves|NSJSONReadingMutableContainers error:nil];
            NSArray *array = dic[@"RESULT"];
            self.tabulationArray = [NSMutableArray array];
            for (NSDictionary *dic in array) {
                NewsTabulationData *cellData = [[NewsTabulationData alloc] init];
                [cellData setValuesForKeysWithDictionary:dic];
                [_tabulationArray addObject:cellData];
                [cellData release];
            }
            //            [self.tableView reloadData];
            //            [self stopAnimating];
        });
        dispatch_async(dispatch_get_main_queue(), ^{
            [self stopAnimating];
            [_TView reloadData];
        });
    }
}


//- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
//{
//    return 100;
//}

//- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
//{
//    return 160;
//}

//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    return 50;
//}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _tabulationArray.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return CELLHEIGHT;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"new";
    NewsTableCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[NewsTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier height:CELLHEIGHT];
    }
    NewsTabulationData *cellData = _tabulationArray[indexPath.row];
    if (cellData.image ==nil)
    {
        [cellData addObserver:self forKeyPath:@"image" options:NSKeyValueObservingOptionNew context:[indexPath retain]];
        [self.obserArray addObject:cellData];
//        [cellData removeObserver:self forKeyPath:@"image"];
    }
   
    cell.cellData = cellData;
    return cell;
}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    NSIndexPath *indexPath = (NSIndexPath *)context;
    NSArray *array = [_TView indexPathsForVisibleRows];
    NewsTableCell *cell = (NewsTableCell *)[_TView cellForRowAtIndexPath:indexPath];
    if ([array containsObject:indexPath]) {
        UIImage *image = (UIImage *)[change objectForKey:@"new"];
        cell.image_View.image = image;
    }
    [indexPath release];
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//    NewDetailViewController *newsDetail = [[NewDetailViewController alloc] init];
//    newsDetail.newsId = [_tabulationArray[indexPath.row] Id];
//    [self.navigationController pushViewController:newsDetail animated:YES];
//    [newsDetail release];
    
    NewDetailViewController *newsDetail = [[NewDetailViewController alloc] init];
    newsDetail.newsId = [_tabulationArray[indexPath.row] Id];
    UINavigationController *newNVC = [[UINavigationController alloc] initWithRootViewController:newsDetail];
    [newNVC setModalTransitionStyle:UIModalTransitionStyleFlipHorizontal];
    [self presentViewController:newNVC animated:YES completion:^{
        
    }];
    [newsDetail release];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
